<template>
  <div class="transaction-add">
    <h1>库存流水添加</h1>
 
    <el-form ref="transactionForm" :model="form" label-width="140px" style="margin-top: 20px;" :rules="formRules">
    
      <el-form-item label="源单据ID" prop="yuandanju">
        <el-input v-model="form.yuandanju" readonly></el-input>
      </el-form-item>
      <el-form-item label="源单据类型" prop="yuandanlei">
        <el-input v-model="form.yuandanlei" readonly value="TRANSFER"></el-input>
      </el-form-item>
      <el-form-item label="仓库ID" prop="cangkuid">
        <el-input v-model="form.cangkuid" readonly></el-input>
      </el-form-item>
      <el-form-item label="操作员ID" prop="yuangongid">
        <el-input v-model="form.yuangongid" readonly :value="currentUserId"></el-input>
      </el-form-item>

      <el-form-item label="备注" prop="zhumin">
        <el-select v-model="form.zhumin" @change="syncTransactionType" placeholder="请选择备注类型">
          <el-option label="调拨类型" value="调拨类型"></el-option>
          <el-option label="采购入库" value="采购入库"></el-option>
          <el-option label="生产入库" value="生产入库"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="交易类型" prop="jiaoyilei">
        <el-input v-model="form.jiaoyilei" readonly placeholder="选择备注后自动生成"></el-input>
      </el-form-item>
        <!-- 3. 勾选的明细数据（展示） -->
      <el-form-item label="明细数据" prop="selectedDetails">
        <el-table :data="selectedDetails" border>
          <el-table-column label="物料ID" prop="materialid"></el-table-column>
          <el-table-column label="批次号" prop="batchno"></el-table-column>
          <el-table-column label="已出库" prop="shippedquantity"></el-table-column>
          <el-table-column label="已入库" prop="receivedquantity"></el-table-column>
          <el-table-column label="交易数量" prop="jiaoyishu">
            <template #default="scope">
              {{ scope.row.shippedquantity - scope.row.receivedquantity }}
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitTransaction">提交流水</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import request from '@/api/request';
import { ElMessage, ElForm } from 'element-plus';

// 状态变量
const form = ref({
  yuandanju: '', 
  yuandanlei: 'TRANSFER', 
  cangkuid: '',
  yuangongid: 'admin', 
  zhumin: '', 
  jiaoyilei: '' 
});
const selectedDetails = ref([]); 
const currentUserId = ref('admin');
const router = useRouter();
const transactionForm = ref(null);


const formRules = ref({
  zhumin: [{ required: true, message: '请选择备注类型', trigger: 'change' }],
  jiaoyilei: [{ required: true, message: '请选择备注生成交易类型', trigger: 'change' }]
});


onMounted(() => {

  const transferMain = JSON.parse(localStorage.getItem('transferMain') || 'null');
  const details = JSON.parse(localStorage.getItem('selectedDetails') || '[]');


  if (!transferMain || details.length === 0) {
    ElMessage.error("请从调拨单页面发起提交流水操作");
    router.push("/warehouse/diaobo");
    return;
  }

  form.value.yuandanju = transferMain.id; 
  form.value.cangkuid = transferMain.toWarehouseid; 
  selectedDetails.value = details;
});


const syncTransactionType = (val) => {
  switch (val) {
    case "调拨类型":
      form.value.jiaoyilei = "TO";
      break;
    case "采购入库":
      form.value.jiaoyilei = "PO_IN";
      break;
    case "生产入库":
      form.value.jiaoyilei = "MO_OUT";
      break;
    default:
      form.value.jiaoyilei = "";
  }
};

const submitTransaction = async () => {
  // 表单验证
  const formEl = transactionForm.value;
  if (!formEl) return;
  await formEl.validate();

  const transactionList = selectedDetails.value.map(detail => ({
    transactionType: form.value.jiaoyilei, // 交易类型
    sourceDocId: form.value.yuandanju, // 源单据ID
    sourceDocType: form.value.yuandanlei, // 源单据类型
    warehouseId: form.value.cangkuid, // 仓库ID
    materialId: detail.materialid, // 明细materialid→流水wulianid
    batchNo: detail.batchno, // 明细batchno→流水picihao
    quantity: detail.shippedquantity - detail.receivedquantity, // 交易数量（自动带正负）
    transactionTime: new Date().toISOString(), // 交易时间
    operatorId: form.value.yuangongid, // 操作员ID
    remarks: form.value.zhumin // 备注
  }));


  try {
    const res = await request({
      method: "post",
      url: "/inventory_sss/add",
      data: transactionList
    });
    if (res.data?.success) {
      ElMessage.success("流水提交成功");
      localStorage.removeItem('transferMain');
      localStorage.removeItem('selectedDetails');
      router.push("/warehouse/transaction"); 
    } else {
      ElMessage.error("提交失败：" + (res.data?.message || "未知错误"));
    }
  } catch (err) {
    ElMessage.error("提交异常：" + err.message);
  }
};

const cancel = () => {
  localStorage.removeItem('transferMain');
  localStorage.removeItem('selectedDetails');
  router.push("/warehouse/diaobo");
};
</script>

<style scoped>
.transaction-add {
  padding: 20px;
}
</style>